# -*- coding:utf-8 -*-

import codecs

CODE_UTF_8 = "utf-8"
CODE_UTF_8_BOM = "utf_8_sig"
CODE_ASCII = "cp936"

class _readLua:
    """ """
    def __init__(self,filename,readmode,readcode):
        """ """
        self.readMode = readmode;
        self.encoding = readcode;
        self.data = self.__commentDel(filename);
        
    def readConf(self,nstr):
        if  nstr.find(",") != -1:
            nlist = self.readLevelList(nstr);
        else:
            nlist = [nstr]
        attr = {}
        arr = []
        for i in nlist:
            k,v = self.readKeyValue(i);
            #print k
            if k:
                k = self.formatValue(k);
                if v.find("=") == -1:
                    attr[k] = self.formatValue(v);
                else:
                    attr[k] = self.readConf(v);
                    #arr.append(self.formatValue(k));
            else:
                if v.find("=") == -1:
                    attr[k] = self.formatValue(v);
                else:
                    arr.append(self.readConf(v));
                    #print arr
        if len(arr)>0:
            return arr
        return attr
        
    def formatValue(self,value):
        if value.count(",") >1:
            return value.split(",")
        value = value.replace("{","")
        value = value.replace("}","")
        value = value.replace(",","")
        value = value.replace(" ","")
        #value = value.decode("gbk2312").encode("utf-8")
        return value
        
    def readBraceGroup(self,nstr,start="{",end="}"):
        roots = []
        lenght = len(nstr);
        if nstr.find(start) == -1:
            nstr.replace("},","");
            nstr.replace("}");
            roots.append(nstr);
        else:
            left_kh = 0;
            right_kh = 0;
            sindex = 0;
            eindex = 0 ;
            for i in range(lenght):
                if nstr[i] == start:
                    left_kh += 1;
                if nstr[i] == end:
                    right_kh += 1
                if left_kh>0 and left_kh == right_kh:
                    eindex = i+2;
                    if eindex >= lenght:
                        eindex = lenght
                    roots.append(nstr[sindex:eindex]);
                    sindex = eindex;
                    left_kh = 0;
                    right_kh = 0;
        return roots
        
    def readLevelList(self,nstr):
        levels = []
        lenght = len(nstr);
        isBrace = 0;
        sindex = 0;
        eindex = 0;
        left_kh = 0;
        right_kh = 0;
        for i in range(lenght):
            if nstr[i] == "," and isBrace == 0 or i+1==lenght:
                eindex = i+1
                if eindex >= lenght:
                    eindex = lenght
                levels.append(nstr[sindex:eindex])
                sindex = eindex;
            if nstr[i] == "{":
                left_kh += 1;
            if nstr[i] == "}":
                right_kh += 1
            if left_kh>0 and left_kh != right_kh:
                isBrace = 1
            elif left_kh>0 and left_kh == right_kh:
                isBrace = 0;
                left_kh = 0;
                right_kh = 0;
            else:
                pass
        return levels
        
    def readKeyValue(self,nstr):
        """ """
        key = None
        value = None
        if nstr.startswith("{") and nstr.endswith("},") != -1:
            value = self.seBroceDel(nstr);
        elif nstr.find("=") == -1:
            value = self.seBroceDel(nstr); 
        else:
            index = nstr.index("=");
            key = nstr[:index]
            value = self.seBroceDel(nstr[index+1:])
        return key,value
        
    def seBroceDel(self,nstr):
        if nstr.startswith("{") and nstr.endswith("},"):
            if nstr.count("{") == nstr.count("}"):
                return nstr[1:-2]
            print "error_1"
        elif nstr.startswith("{") and nstr.endswith("}"):
            if nstr.count("{") == nstr.count("}"):
                return nstr[1:-1]
            print "error_2"
        else:
            if nstr.count("{") == nstr.count("}"):
                return nstr
            return nstr
            
    def __commentDel(self,filename):
        pf = codecs.open(filename,self.readMode,encoding=self.encoding);
        buff = "";
        flag = 0
        for line in pf:
            if line.find("--[[")!= -1:
                buff += self.__strBefore(line,"--");
                flag = 1
                continue
            if line.find("]]") != -1:
                buff += self.__strEnd(line,"]]")
                flag = 0
                continue
            if line.find("--") != -1:
                buff += self.__strBefore(line,"--");
                continue
            if flag == 1:
                continue
            else:
                buff += line;
        pf.close();
        buff = buff.replace("\n","") #
        buff = buff.replace("\r","") #
        buff = buff.replace("\t","") #
        buff = buff.replace(" ","")  #
        #bom = unicode(codecs.BOM_UTF8, "utf8" )
        #buff = buff.replace(bom, "")
        return buff;
        
    def __strBefore(self,nstr,rp):
        index = nstr.index(rp)
        if index==0:
            return ""
        elif index == -1:
            return nstr
        else:
            return nstr[:index]
            
    def __strEnd(self,nstr,rp):
        index = nstr.index(rp) + len(rp);
        if index  == len(nstr):
            return ""
        res = nstr[index:];
        return self.__isComment(res)
            
    def __isComment(self,nstr):
        if nstr.find("--") == -1:
            return nstr
        index = nstr.index("--");
        if index == 0 or index + len("--")>=len(nstr):
            return ""
        return nstr[:index]
        
def readFile(filename,mode="r",code="cp936"):
    p = _readLua(filename,mode,code);
    return p.readConf(p.data)

if __name__ == "__main__":
    _help="""\
import readLua
data = readLua.readFile(filename,mode="r",code="cp936")
mode --> r or rb
code --> "utf-8","utf_8_sig","cp936" 
CODE_UTF_8 = "utf-8"
CODE_UTF_8_BOM = "utf_8_sig"
CODE_ASCII = "cp936"\
    """
    print _help